const logger = require('./logger');

module.exports = (err, req, res, next) => {
  // 设置默认值
  err.status = err.status || 500;
  err.message = err.message || 'Internal Server Error';
  
  // 记录错误
  logger.error(`${err.status} - ${err.message} - ${req.originalUrl} - ${req.method} - ${req.ip}`);
  
  // 生产环境隐藏错误详情
  const response = {
    code: err.status,
    message: err.message
  };
  
  if (process.env.NODE_ENV !== 'production') {
    response.stack = err.stack;
  }
  
  // 验证错误处理
  if (err.errors) {
    response.errors = {};
    Object.keys(err.errors).forEach((key) => {
      response.errors[key] = err.errors[key].message;
    });
  }
  
  res.status(err.status).json(response);
};